<?php
/**
 * 用户管理
 * @link https://www.leadshop.vip/
 * @copyright Copyright ©2020-2021 浙江禾成云计算有限公司
 */

namespace store\api;

use framework\common\BasicController;
use store\models\Store;
use Yii;
use yii\base\BaseObject;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use yii\widgets\LinkPager;

class IndexController extends BasicController
{

    public $modelClass = 'system\models\Account';

    /**
     * 重写父类
     * @return [type] [description]
     */
    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        unset($actions['view']);
        unset($actions['create']);
        unset($actions['update']);
        return $actions;
    }



    /**
     * 处理数据搜索问题
     * @return [type] [description]
     */
    public function actionSearch()
    {
        $modelClass = $this->modelClass;
        //获取头部信息
        $headers = Yii::$app->getRequest()->getHeaders();
        //获取分页信息
        $pageSize = $headers->get('X-Pagination-Per-Page') ?? 20;
        //订单分组
        $keyword = Yii::$app->request->get('keyword', []);
        $page = Yii::$app->request->get('page',1);

        $AppID = Yii::$app->params['AppID'];
        //$where = ['AppID' => $AppID];
        $where = [];
        $where = ['deleted'=>0];

        //关键词搜索
        $search = $keyword['search'] ?? false;
        if ($search) {
            $where = ['and', $where, ['or', ['like', 'store_name', $search], ['like', 'store_rename', $search], ['store_phone' => $search],['seo_keywords' => $search], ['store.store_address' => $search]]];
        }

        //用户来源筛选
        $source = $keyword['store_state'] ?? false;
        if ($source) {
            $where = ['and', $where, ['store_state' => $source]];
        }



        //注册时间区间
        $created_time_start = $keyword['created_time_start'] ?? false;
        if ($created_time_start > 0) {
            $where = ['and', $where, ['>=', 'created_time', $created_time_start]];
        }
        $created_time_end = $keyword['created_time_end'] ?? false;
        if ($created_time_end > 0) {
            $where = ['and', $where, ['<=', 'created_time', $created_time_end]];
        }


        //处理排序
        $sort    = isset($keyword['sort']) && is_array($keyword['sort']) ? $keyword['sort'] : [];
        $orderBy = [];
        if (empty($sort)) {
            $orderBy = ['created_time' => SORT_DESC];
        } else {
            foreach ($sort as $key => $value) {
                    if (!sql_check($key)) {
                        $orderBy[$key] = $value === 'ASC' ? SORT_ASC : SORT_DESC;
                    }
            }
        }
        $totalcount = M('store', 'Store')::find()
        ->alias('store')
        ->where($where)->count();
        $pages = new Pagination([
            'totalCount' => $totalcount,
            'pageSizeLimit' => [$page, $pageSize]
        ]);
       // $data = M('store', 'Store')::find()->all();
       $data= M('store', 'Store')::find()->where($where)->orderBy($orderBy)->asArray();
       $data = new ActiveDataProvider(
            [
                'query'      => $data,

                'pagination' => [
                    'pageSizeLimit' => [$page, $pageSize]
                ]
            ]
        );
        $list = $data->getModels();
        foreach ($list as &$vab) {
            $resultd = $modelClass::find()
                ->where(['id' => $vab['user_id']])
                ->andWhere(['is_deleted' => 0])
                ->asArray()
                ->one();
            if(!$resultd){
                $vab['account_name'] = '員工已刪除';
            }else{
                $vab['account_name'] =  $resultd['nickname'];
            }
        }
        //将所有返回内容中的本地地址代替字符串替换为域名
        $list = str2url($list);
        $data->setModels($list);
        $totalpage = ceil($totalcount/$pageSize);
        $datab['totalPage']= $totalpage;
        $datab['list']= $data;
        $datab['total']= $pages;

        return $datab;
    }

    /**
     * 回收站
     * @return [type] [description]
     */
    public function actionDelete()
    {
        $id      = Yii::$app->request->get('id', false);
        if (!$id) {
            Error('ID缺失');
        }
        $id   = explode(',', $id);
        $data = [
            'deleted' => 1,
            'deleted_time' => time(),
            'updated_time' => time(),
        ];
        $result = M('store', 'Store')::find()
            ->where(['id' => $id])
            ->asArray()
            ->one();

        if (empty($result)) {
            Error('門店找不到');
        }

        $result =  M('store', 'Store')::updateAll($data, ['id' => $id]);
        if ($result) {
            return $result;
        } else {
            Error('删除失败');
        }


    }


    /**
     * 用户详情
     * @return [type] [description]
     */
    public function actionView()
    {
        $id = Yii::$app->request->get('id', false);


        $result = M('store', 'Store')::find()
            ->where(['id' => $id])
            ->asArray()
            ->one();

        if (empty($result)) {
            Error('門店找不到');
        }
        return $result;
    }



    public function actionCreate()
    {
        $post = Yii::$app->request->post();
        $post_values = array_values($post);
        $post_keys = array_keys($post);
        $post = array_combine($post_keys, $post_values);
        $time = time();
        if(strlen($post['id'])>0) {
            $model =  M('store', 'Store')::findOne($post['id']);

            if (empty($model)) {
                Error('門店不存在');
            }
            $scenarios = 'update';
            if ($model['store_state'] == 1) {
                $post['store_state'] = 2;
            }
            $post['updated_time'] = $time;
        } else {
            $model                = new Store();
            $scenarios            = 'create';
            $post['store_state']  = 2;
            $post['created_time'] = $time;
            $post['updated_time'] = $time;
        }
        $transaction = Yii::$app->db->beginTransaction(); //启动数据库事务
        //统一替换本地文件地址
       $post = url2str($post);

        $model->setScenario($scenarios);
        $model->setAttributes($post);
        if ($model->validate()) {
            $res = $model->save();
            if ($res) {
                $id = $model->id;
                $transaction->commit();
                return ['id' => $id];
            } else {
                $transaction->rollBack();
                Error('保存失败');
            }
        }
        return $model;

    }

    /**
     * 用户修改
     * @return [type] [description]
     */
    public function actionUpdate()
    {
        //获取操作
        $behavior = Yii::$app->request->get('behavior', '');

        switch ($behavior) {
            case 'setting': //用户设置
                return $this->setting();
                break;
            default:
                Error('未定义操作');
                break;
        }
    }

    /**
     * 电话和姓名设置
     * @return [type] [description]
     */
    public function setting()
    {
        $id   = Yii::$app->request->get('id', false);
        $post = Yii::$app->request->post();

        $model = M('users', 'User')::findOne($id);
        if (empty($model)) {
            Error('用户不存在');
        }

        if (N('mobile')) {
            if (!preg_match("/^1[0-9]{10}$/", $post['mobile'])) {
                Error('请填写正确手机号');
            }
            $check = M('users', 'User')::find()->where(['and', ['mobile' => $post['mobile']], ['<>', 'id', $id]])->with(['oauth' => function ($query) {
                $query->select('UID,type');
            }])->asArray()->all();
            if (!empty($check)) {
                foreach ($check as $value) {
                    if ($value['oauth']['type'] === $model->oauth->type) {
                        Error('手机号已存在');
                    }
                }
            }
        }

        $model->setScenario('setting');
        $model->setAttributes($post);
        if ($model->validate()) {
            $res = $model->save();
            if ($res) {
                return $model;
            } else {
                Error('保存失败');
            }

        }
        return $model;
    }
}
